<template>
  <!-- 物业库 - 新增/编辑物业 -->
  <div class="propertyAddPage">
    <el-form
      :inline="true"
      :model="baseForm"
      ref="baseFormRef"
      :rules="baseState.rules"
      class="demo-form-inline"
      label-position="right"
      label-width="120px"
    >
      <el-row>
        <el-col :span="7">
          <el-form-item style="width: 100%" label="物业类型：" prop="type">
            <el-select
              v-model="baseForm.type"
              style="width: 100%"
              placeholder="选择物业类型"
            >
              <el-option
                v-for="item in typeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            label="物业服务单位名称："
            label-width="200px"
            prop="propertyCompanyName"
          >
            <el-input
              v-model="baseForm.propertyCompanyName"
              maxlength="20"
              clearable
              placeholder="请输入物业服务单位名称(20字以内)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item
            style="width: 100%"
            label="联系人姓名："
            prop="contactUserName"
          >
            <el-input
              v-model="baseForm.contactUserName"
              placeholder="请输入联系人姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            label-width="200px"
            label="联系电话："
            prop="contactPhone"
          >
            <el-input
              v-model="baseForm.contactPhone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item
            style="width: 100%"
            label="物业费单价："
            prop="propertyFeeUnitPrice"
          >
            <el-input
              v-model="baseForm.propertyFeeUnitPrice"
              clearable
              @input="
                baseForm.propertyFeeUnitPrice = limitInputNum(
                  baseForm.propertyFeeUnitPrice,
                  9,
                  2,
                  true
                )
              "
              placeholder="请输入物业费单价 (元)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display: flex; justify-content: center">
        <el-button class="button_cancel2" plain @click="cancelAdd">取消</el-button>
        <el-button
          class="button_view"
          type="primary"
          :disabled="subDisFlag"
          @click="submitAdd"
        >
          确认
        </el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElMessage,
} from "element-plus";
import { Plus, Remove } from "@element-plus/icons-vue";
import {checkEmptyString, getURLhandler, limitInputNum} from "@/common/utils/GlobalUtils";
import { recruitTypeOptionsArr } from "@/common/dict/dictCollect";
import { propertyApi } from "@/api/assets";
import { useRoute, useRouter } from "vue-router";
import {useStore} from "vuex";
import {clearCache} from "@/utils/createRoutes";
const route = useRoute();

const getPropertyId = getURLhandler(route.path).id;
const pageType = getURLhandler(route.path).pageType;

const router = useRouter();
const store = useStore();

// 去掉第一个
const typeOptionsArr = _.drop(recruitTypeOptionsArr);
// 提交按钮状态
const subDisFlag = ref(false);

const baseFormRef = ref(null);
const baseForm = reactive({
  propertyCompanyName: "",
  type: null,
  propertyFeeUnitPrice: "",
  contactPhone: "",
  contactUserName: "",
});

const checkPhone = (rule, value, callback) => {
  const reg = /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!value) {
    callback(new Error("请输入联系电话"));
  } else {
    if (!reg.test(value)) {
      callback(new Error("请输入正确的手机号码格式"));
    } else {
      callback();
    }
  }
};
const baseState = reactive({
  rules: {
    type: [{ required: true, trigger: "change", message: "请选择物业类型" }],
    propertyCompanyName: [
      { required: true, trigger: "blur", message: "请输入物业服务单位名称" },
    ],
    contactUserName: [
      { required: true, trigger: "change", message: "请输入联系人姓名" },
    ],
    contactPhone: [{ required: true, trigger: "blur", validator: checkPhone }],
  },
});

const cancelAdd = () => {
  clearCache({title:'新增物业'});
  router.push({ path: "/asset/company/propertyInformation" });
};

// 提交
const submitAdd = () => {
  baseFormRef.value.validate((vaild) => {
    if (vaild) {
      subDisFlag.value = true;
      let params = { ...baseForm };
      if (pageType === "add") {
        // 新增
        propertyApi.saveProperty(params).then((res) => {
          const { code } = res;
          if (code === '200') {
            ElMessage.success("新增物业成功");
            setTimeout(() => {
              router.push({ path: "/asset/company/propertyInformation" });
              subDisFlag.value = false;
            }, 1000);
            clearCache({title:'新增物业'});
          } else {
            subDisFlag.value = false;
          }
        });
      }

      if (pageType === "edit") {
        // 编辑
        params.propertyCompanyId = getPropertyId;
        propertyApi.saveProperty(params).then((res) => {
          const { code } = res;
          if (code === '200') {
            ElMessage.success("编辑物业信息成功");
            setTimeout(() => {
              router.push({ path: "/asset/company/propertyInformation" });
              subDisFlag.value = false;
            }, 1000);
          } else {
            subDisFlag.value = false;
          }
        });
      }
    }
  });
};

// 编辑时获取信息
const initPropertyInfo = () => {
  propertyApi.getPropertyInfo(getPropertyId).then((res) => {
    const { code, data } = res;
    Object.keys(baseForm).forEach((key) => {
      baseForm[key] = data[key];
      if (key === "type") {
        baseForm[key] = data[key] - 0;
      }
    });
  });
};

/**
 * 监听form,用户在输入
 */
watch(baseForm,(value)=>{
    store.commit("setPropertyForm", baseForm);
},{deep:true})

const initForm = () => {
    if (store.state.collaborativeApproval.propertyForm) {
        for (let key in store.state.collaborativeApproval.propertyForm) {
            for (let key2 in baseForm) {
                baseForm[key] = store.state.collaborativeApproval.propertyForm[key];
            }
        }
    }
};


onMounted(() => {
  if (pageType === "edit") {
    initPropertyInfo();
  }
  if (pageType !== "edit") {
      initForm();
  }
});
</script>

<style lang="scss" scoped>
.propertyAddPage {
  .btnStyle {
    width: 76px;
  }
}
</style>

<style lang="scss" scoped>
.propertyAddPage {
  :deep(.demo-form-inline) {
    .el-form-item {
      margin-bottom: 34px;
      .el-form-item__label {
        font-weight: 500;
        font-size: 16px;
        font-family: SourceHanSansMedium;
      }
      .el-form-item__content {
        .el-date-editor.el-input,
        .el-date-editor.el-input__wrapper {
          width: 100%;
          .el-input__wrapper {
            width: 100%;
          }
        }
      }
    }
    .noBgBox {
      .el-form-item__content {
        background: none;
      }
    }
  }
}
</style>
